﻿using ProxyServer.EntityFrameworkCore;
using ProxyServer.Quartz.Jobs;
using Quartz;

namespace ProxyServer.Quartz;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddQuartzServices(this IServiceCollection services)
    {
        services.AddQuartz().AddQuartzHostedService();

        return services;
    }

    public static async Task RegisterJobs(this WebApplication app)
    {
        using (var scope = app.Services.CreateAsyncScope())
        {
            var schd = await scope.ServiceProvider.GetRequiredService<ISchedulerFactory>().GetScheduler();

            await schd.AddJob(JobBuilder.Create<CheckAccountJob>().WithIdentity(CheckAccountJob.Key).Build(), true, true);

            var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
            var logger = scope.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger(nameof(RegisterJobs));
            var serviceIds = db.Services.Select(x => x.Id).ToList();

            foreach (var serviceId in serviceIds)
            {
                var jobKey = CheckServiceCertificateJob.BuildServiceJobKey(serviceId);
                await schd.AddJob(JobBuilder.Create<CheckServiceCertificateJob>()
                    .WithIdentity(jobKey)
                    .StoreDurably(true)
                    .UsingJobData(new JobDataMap
                    {
                        [CheckServiceCertificateJob.ServiceId] = serviceId
                    }).Build(), true, true);

                logger.LogInformation("Created CheckServiceCertificateJob for service {ServiceId}", serviceId);
            }
        }
    }
}
